<?php
/**
 * 自动为 app/logic 下的每个类生成带方法签名和 @see 注释的 service 文件（无 interface 限定，方法体留空）
 * 用法：php scripts/generate_services.php
 */

$logicPath = __DIR__ . '/../app/logic';
$servicePath = __DIR__ . '/../app/service';

if (!is_dir($servicePath)) {
    mkdir($servicePath, 0755, true);
}

foreach (glob($logicPath . '/*.php') as $logicFile) {
    $logicClass = basename($logicFile, '.php');
    $serviceName = str_replace('Logic', 'Service', $logicClass);

    // 反射获取方法
    require_once $logicFile;
    $fqcn = "app\\logic\\$logicClass";
    $ref = new ReflectionClass($fqcn);

    $methods = [];
    foreach ($ref->getMethods(ReflectionMethod::IS_PUBLIC) as $method) {
        if ($method->isStatic() && $method->getDeclaringClass()->getName() === $fqcn) {
            $params = [];
            foreach ($method->getParameters() as $param) {
                $paramStr = '';
                if ($param->hasType()) {
                    $paramStr .= $param->getType() . ' ';
                }
                $paramStr .= '$' . $param->getName();
                if ($param->isDefaultValueAvailable()) {
                    $default = var_export($param->getDefaultValue(), true);
                    $paramStr .= " = $default";
                }
                $params[] = $paramStr;
            }
            $returnType = $method->hasReturnType() ? ': ' . $method->getReturnType() : '';
            $methods[] = [
                'name' => $method->getName(),
                'params' => implode(', ', $params),
                'return' => $returnType,
            ];
        }
    }

    // 生成 service 类
    $serviceCode = "<?php\nnamespace app\\service;\n\nuse app\\logic\\$logicClass;\n\nclass $serviceName\n{\n    protected static \$instance;\n\n    public static function instance()\n    {\n        if (!self::\$instance) {\n            throw new \\RuntimeException('$serviceName implementation not registered');\n        }\n        return self::\$instance;\n    }\n\n    public static function register(\$impl)\n    {\n        self::\$instance = \$impl;\n    }\n";
    foreach ($methods as $m) {
        $serviceCode .= "\n    /**\n     * @see \\app\\logic\\$logicClass::{$m['name']}\n     */\n    public static function {$m['name']}({$m['params']}){$m['return']} {}\n";
    }
    $serviceCode .= "}\n";

    file_put_contents($servicePath . "/$serviceName.php", $serviceCode);
    echo "Generated: $servicePath/$serviceName.php\n";
}